package cn.com.vodcod;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class MapUtils {
	
	public static Map<Integer, Integer> sortMapByValue(Map<Integer, Integer> oriMap) {
		Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
		List<Map.Entry<Integer, Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>(
				oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());
		Iterator<Map.Entry<Integer, Integer>> iter = entryList.iterator();
		Map.Entry<Integer, Integer> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}
	
	static class MapValueComparator implements Comparator<Map.Entry<Integer,Integer>> {
		@Override
		public int compare(Entry<Integer,Integer> me1, Entry<Integer,Integer> me2) {
			int count1 = me1.getValue();
			int count2 = me2.getValue();
			if(count1==count2){
				return me1.getKey()>me2.getKey()?-1:me1.getKey()==me2.getKey()?0:1;
			}
			return count1>count2?-1:count1==count2?0:1;
		}
	}
	
	public static void main(String[] args) {
		Map<Integer,Integer> map = new HashMap<>();
		map.put(1, 3);
		map.put(2, 4);
		map.put(4, 1);
		map.put(14, 3);
		map.put(12, 4);
		Map<Integer,Integer> map2  = sortMapByValue(map);
		for(Map.Entry<Integer,Integer> m :map2.entrySet()){
			System.out.println("value="+m.getValue()+",key="+m.getKey());
		}
	}
}
